package com.tbmob.tb_h5;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.View;

import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.lang.ref.WeakReference;

public class MyWebViewClient extends WebViewClient {

    private final WeakReference<MainActivity> reference;

    MyWebViewClient(MainActivity activity) {
        reference = new WeakReference<>(activity);
    }

    //重写父类方法，让新打开的网页在当前的WebView中显示
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        MainActivity activity = reference.get();
        activity.isBackPressedSupport = true;
        if (url.startsWith("http:") || url.startsWith("https:")) {
            //view.loadUrl(url);
            return false;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            activity.startActivity(intent);
        } catch (Exception e) {
            Log.e("MyWebViewClient", "shouldOverrideUrlLoading_Exception=" + e);
        }
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        MainActivity activity = reference.get();
        activity.progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        MainActivity activity = reference.get();
        try {
            if (url.startsWith("weixin://wap/pay?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                activity.startActivity(intent);
            }
        } catch (Exception e) {
            Log.e("MyWebViewClient", "onPageStarted_Exception=" + e);
        }
        super.onPageStarted(view, url, favicon);
        activity.progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed();
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
    }
}
